<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { MeetingVO } from '#/api/meeting/model';

import { computed } from 'vue';

// import { useAccess } from '@vben/access';
import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { getVxePopupContainer } from '@vben/utils';

import {
  Dropdown,
  Empty,
  Menu,
  MenuItem,
  Modal,
  Popconfirm,
  Space,
} from 'ant-design-vue';

import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import {
  // meetingExport,
  meetingInfo,
  meetingPage,
  meetingRemove,
  // meetingUpdateStatus,
} from '#/api/meeting';
import {
  meetingEnrollDownloadImportTemplate,
  meetingEnrollImport,
} from '#/api/meeting/enroll';
import { ColorTag } from '#/components/dict';
import importModal from '#/components/import/src/import-modal.vue';
import { DetailsModal } from '#/components/modal';
import qrcodeModal from '#/components/modal/src/qrcode-modal.vue';
// import { TableSwitch } from '#/components/table';
// import { commonDownloadExcel } from '#/utils/file/download';

import { columns, detailsSchema, querySchema } from './data';
import meetingDrawer from './meeting-drawer.vue';
import meetingEnrollTableDrawer from './meeting-enroll-table-drawer.vue';
import meetingNotifyTableDrawer from './meeting-notify-table-drawer.vue';

const props = withDefaults(defineProps<Props>(), {
  type: 1,
});

// const emit = defineEmits<{ reload: [] }>();

interface Props {
  type?: 1 | 2;
}

const meetingTypeName = computed(() => {
  const map = {
    1: '非展期会议',
    2: '展期会议',
  };

  return map[props.type];
});

// const { hasAccessByCodes } = useAccess();

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  wrapperClass:
    'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 2xl:grid-cols-4',
  fieldMappingTime: [
    [
      'time',
      ['startTime', 'endTime'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    // trigger: 'row',
  },
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await meetingPage({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
          type: props.type,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  // showOverflow: false,
  id: `meeting-list-${props.type}`,
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [MeetingDetailsModal, detailsModalApi] = useVbenModal({
  connectedComponent: DetailsModal,
});

function handlePreview(record: MeetingVO) {
  detailsModalApi.setData(record);
  detailsModalApi.open();
}

const [MeetingDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: meetingDrawer,
});

function handleAdd() {
  drawerApi.setData({ type: props.type });
  drawerApi.open();
}

async function handleEdit(row: MeetingVO) {
  drawerApi.setData({ type: props.type, id: row.id });
  drawerApi.open();
}

async function handleDelete(row: MeetingVO) {
  await meetingRemove(row.id);
  await tableApi.query();
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: MeetingVO) => row.id);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await meetingRemove(ids);
      await tableApi.query();
    },
  });
}

// function handleDownloadExcel() {
//   commonDownloadExcel(
//     meetingExport,
//     `${meetingTypeName.value}数据`,
//     tableApi.formApi.form.values,
//     {
//       fieldMappingTime: formOptions.fieldMappingTime,
//     },
//   );
// }

// async function statusUpdate(row: MeetingVO) {
//   const data = {
//     id: row.id,
//     status: row.status,
//   };
//   await meetingUpdateStatus(data);
// }

// 报名详情
const [MeetingEnrollTableDrawer, meetingEnrollTableDrawerApi] = useVbenDrawer({
  connectedComponent: meetingEnrollTableDrawer,
  destroyOnClose: true,
});

function viewRegisterList(row: MeetingVO) {
  meetingEnrollTableDrawerApi.setData({ meetingId: row.id, name: row.name });
  meetingEnrollTableDrawerApi.open();
}

// 批量导入报名
const [ImportRegisterModal, importRegisterModalApi] = useVbenModal({
  connectedComponent: importModal,
  destroyOnClose: true,
});

function viewRegisterBatch(row: MeetingVO) {
  importRegisterModalApi.setData({ query: { meetingId: row.id } });
  importRegisterModalApi.open();
}

async function handleImportRegisterSuccess() {
  await tableApi.query();
}

// 发送通知
const [MeetingNotifyTableDrawer, meetingNotifyTableDrawerApi] = useVbenDrawer({
  connectedComponent: meetingNotifyTableDrawer,
  destroyOnClose: true,
});

function viewNotification(row: MeetingVO) {
  meetingNotifyTableDrawerApi.setData({ id: row.id, name: row.name });
  meetingNotifyTableDrawerApi.open();
}

// 签到二维码（听众）
const [QrcodeModal, qrcodeModalApi] = useVbenModal({
  connectedComponent: qrcodeModal,
  destroyOnClose: true,
});

function viewQrcode1(row: MeetingVO) {
  qrcodeModalApi.setData({
    modalTitle: `签到二维码（听众）`,
    title: row.name,
    qrcodeUrl: `https://www.iteschina.com/zh-cn/meeting/signin/${row.id}&type=1`,
  });
  qrcodeModalApi.open();
}

// 签到二维码（观众）
function viewQrcode2(row: MeetingVO) {
  qrcodeModalApi.setData({
    modalTitle: `签到二维码（观众）`,
    title: row.name,
    qrcodeUrl: `https://www.iteschina.com/zh-cn/meeting/signin/${row.id}&type=2`,
  });
  qrcodeModalApi.open();
}

// 签到结果二维码
function viewQrcodeResult(row: MeetingVO) {
  qrcodeModalApi.setData({
    modalTitle: `签到结果二维码`,
    title: row.name,
    qrcodeUrl: `https://www.iteschina.com/zh-cn/meeting/signin/${row.id}/result`,
  });
  qrcodeModalApi.open();
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable>
      <template #table-title>
        <main-title :text="`${meetingTypeName}列表`" />
      </template>
      <template #toolbar-tools>
        <Space>
          <!--<a-button-->
          <!--  v-access:code="['meeting:manager:export']"-->
          <!--  @click="handleDownloadExcel"-->
          <!--&gt;-->
          <!--  {{ $t('pages.common.export') }}-->
          <!--</a-button>-->
          <a-button
            :disabled="!vxeCheckboxChecked(tableApi)"
            danger
            type="primary"
            v-access:code="['meeting:manager:remove']"
            @click="handleMultiDelete"
          >
            {{ $t('pages.common.delete') }}
          </a-button>
          <a-button
            type="primary"
            v-access:code="['meeting:manager:add']"
            @click="handleAdd"
          >
            {{ $t('pages.common.add') }}
          </a-button>
        </Space>
      </template>
      <template #meetingTime="{ row }">
        <div>
          <div>{{ row.startTime }} ~ {{ row.endTime }}</div>
        </div>
      </template>
      <!--<template #status="{ row }">-->
      <!--  <TableSwitch-->
      <!--    v-model:value="row.status"-->
      <!--    :api="() => statusUpdate(row)"-->
      <!--    :disabled="!hasAccessByCodes(['meeting:manager:edit'])"-->
      <!--    @reload="tableApi.query()"-->
      <!--  />-->
      <!--</template>-->
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-access:code="['meeting:manager:query']"
            @click.stop="handlePreview(row)"
          >
            {{ $t('pages.common.info') }}
          </ghost-button>
          <ghost-button @click.stop="handleEdit(row)">
            {{ $t('pages.common.edit') }}
          </ghost-button>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <ghost-button
              v-access:code="['meeting:manager:delete']"
              danger
              @click.stop=""
            >
              {{ $t('pages.common.delete') }}
            </ghost-button>
          </Popconfirm>
        </Space>
        <Dropdown placement="bottomRight">
          <template #overlay>
            <Menu>
              <span v-access:code="['meeting:enroll:list']">
                <MenuItem key="registerList" @click="viewRegisterList(row)">
                  报名详情
                </MenuItem>
              </span>
              <span v-access:code="['meeting:enroll:import']">
                <MenuItem key="registerBatch" @click="viewRegisterBatch(row)">
                  批量报名
                </MenuItem>
              </span>
              <span v-access:code="['meeting:notifyTask:list']">
                <MenuItem key="notification" @click="viewNotification(row)">
                  发送通知
                </MenuItem>
              </span>
              <span v-access:code="['meeting:manager:qrcode']">
                <MenuItem key="qrcode1" @click="viewQrcode1(row)">
                  签到二维码（听众）
                </MenuItem>
              </span>
              <span v-access:code="['meeting:manager:qrcode']">
                <MenuItem key="qrcode2" @click="viewQrcode2(row)">
                  签到二维码（观众）
                </MenuItem>
              </span>
              <span v-access:code="['meeting:manager:qrcodeResult']">
                <MenuItem key="qrcodeResult" @click="viewQrcodeResult(row)">
                  签到结果二维码
                </MenuItem>
              </span>
            </Menu>
          </template>
          <a-button size="small" type="link" @click.prevent>
            {{ $t('pages.common.more') }}
          </a-button>
        </Dropdown>
      </template>
    </BasicTable>
    <MeetingDetailsModal
      :columns="detailsSchema()"
      :api="meetingInfo"
      :width="700"
    >
      <template #labels="{ info }">
        <div v-if="info.labels.length > 0" class="flex flex-wrap gap-1">
          <ColorTag
            v-for="tag in info.labels"
            :key="tag.id"
            :color="tag.listClass"
            :label="tag.name"
            :disabled="tag.status === '1'"
            icon="gravity-ui:tag"
          />
        </div>
        <div v-else class="p-5">
          <Empty description="暂无标签" />
        </div>
      </template>
    </MeetingDetailsModal>
    <MeetingDrawer @reload="tableApi.query()" />
    <MeetingEnrollTableDrawer @reload="tableApi.query()" />
    <ImportRegisterModal
      title="导入批量报名"
      :import-api="meetingEnrollImport"
      :download-api="meetingEnrollDownloadImportTemplate"
      @reload="handleImportRegisterSuccess"
    />
    <MeetingNotifyTableDrawer />
    <QrcodeModal />
  </Page>
</template>
